document.addEventListener('DOMContentLoaded', function () {
  // 获取DOM元素
  const locationInput = document.getElementById('location');
  const categoryInput = document.getElementById('category');
  const keywordInput = document.getElementById('keyword');
  const pagesInput = document.getElementById('pages');
  const delayInput = document.getElementById('delay');
  const sortByReviewsCheckbox = document.getElementById('sortByReviews');
  const startScrapeBtn = document.getElementById('startScrape');
  const pauseResumeBtn = document.getElementById('pauseResume');
  const exportDataBtn = document.getElementById('exportData');
  const statusText = document.getElementById('statusText');
  const progressFill = document.getElementById('progressFill');
  const dataCountText = document.getElementById('dataCount');
  const closeWindowBtn = document.getElementById('closeWindow');

  // 添加关闭窗口按钮事件
  if (closeWindowBtn) {
    closeWindowBtn.addEventListener('click', function () {
      window.close();
    });
  }

  // 设置窗口标题
  document.title = 'Yelp Restaurant Data Scraper';

  // 爬取状态
  let isScrapingActive = false;
  let isPaused = false;
  let dataCount = 0;

  // 从存储中加载保存的设置
  chrome.storage.local.get(
    ['location', 'category', 'keyword', 'pages', 'delay', 'sortByReviews'],
    function (result) {
      if (result.location) locationInput.value = result.location;
      if (result.category) categoryInput.value = result.category;
      if (result.keyword) keywordInput.value = result.keyword;
      if (result.pages) pagesInput.value = result.pages;
      if (result.delay) delayInput.value = result.delay;
      if (result.sortByReviews !== undefined)
        sortByReviewsCheckbox.checked = result.sortByReviews;
    }
  );

  // 检查是否有已抓取的数据和当前爬取状态
  chrome.storage.local.get('restaurantData', function (result) {
    if (result.restaurantData && result.restaurantData.length > 0) {
      exportDataBtn.disabled = false;
      dataCount = result.restaurantData.length;
      dataCountText.textContent = `Collected data: ${dataCount} restaurants`;
    }

    // 检查当前爬取状态
    chrome.runtime.sendMessage(
      { action: 'getScrapeStatus' },
      function (response) {
        if (response && response.isRunning) {
          isScrapingActive = true;
          isPaused = response.isPaused;
          dataCount = response.dataCount;

          // 更新UI
          startScrapeBtn.disabled = true;
          pauseResumeBtn.disabled = false;
          pauseResumeBtn.textContent = isPaused ? 'Resume' : 'Pause';
          dataCountText.textContent = `Collected data: ${dataCount} restaurants`;

          // 更新进度条
          if (response.progress) {
            const percentage =
              (response.progress.current / response.progress.total) * 100;
            progressFill.style.width = `${percentage}%`;

            let statusMessage = '';
            if (response.progress.phase === 'collectLinks') {
              statusMessage = `Phase 1: Collecting restaurant links - ${response.progress.current}/${response.progress.total} pages`;
            } else if (response.progress.phase === 'scrapeDetails') {
              statusMessage = `Phase 2: Collecting restaurant details - ${response.progress.current}/${response.progress.total} restaurants`;
            }

            if (isPaused) {
              statusMessage = 'PAUSED - ' + statusMessage;
            }

            statusText.textContent = statusMessage;
          }
        }
      }
    );
  });

  // 保存设置
  function saveSettings() {
    chrome.storage.local.set({
      location: locationInput.value,
      category: categoryInput.value,
      keyword: keywordInput.value,
      pages: pagesInput.value,
      delay: delayInput.value,
      sortByReviews: sortByReviewsCheckbox.checked,
    });
  }

  // 开始抓取按钮点击事件
  startScrapeBtn.addEventListener('click', function () {
    // 保存当前设置
    saveSettings();

    // 禁用按钮，显示正在抓取状态
    startScrapeBtn.disabled = true;
    pauseResumeBtn.disabled = false;
    pauseResumeBtn.textContent = 'Pause';
    statusText.textContent = 'Preparing to scrape...';
    progressFill.style.width = '0%';

    // 重置状态
    isScrapingActive = true;
    isPaused = false;
    dataCount = 0;
    dataCountText.textContent = 'Collected data: 0 restaurants';

    // 构建搜索URL
    const searchParams = new URLSearchParams();

    // 处理搜索关键词
    let searchTerms = '';
    if (categoryInput.value.trim()) {
      searchTerms += categoryInput.value.trim();
    }
    if (keywordInput.value.trim()) {
      if (searchTerms) searchTerms += ' ';
      searchTerms += keywordInput.value.trim();
    }

    if (searchTerms) {
      searchParams.append('find_desc', searchTerms);
    }

    // 处理位置
    const location = locationInput.value.trim() || 'United States';
    searchParams.append('find_loc', location);

    // 添加排序参数
    if (sortByReviewsCheckbox.checked) {
      searchParams.append('sortby', 'review_count');
    }

    const searchUrl = `https://www.yelp.com/search?${searchParams.toString()}`;

    // 发送消息给background脚本开始抓取
    chrome.runtime.sendMessage({
      action: 'startScrape',
      url: searchUrl,
      pages: parseInt(pagesInput.value),
      delay: parseInt(delayInput.value) * 1000, // 转换为毫秒
      sortByReviews: sortByReviewsCheckbox.checked,
    });
  });

  // 暂停/继续按钮点击事件
  pauseResumeBtn.addEventListener('click', function () {
    if (!isScrapingActive) return;

    if (isPaused) {
      // 继续抓取
      chrome.runtime.sendMessage(
        { action: 'resumeScrape' },
        function (response) {
          if (response && response.success) {
            isPaused = false;
            pauseResumeBtn.textContent = 'Pause';
            statusText.textContent = 'Resuming scraping...';
          }
        }
      );
    } else {
      // 暂停抓取
      chrome.runtime.sendMessage(
        { action: 'pauseScrape' },
        function (response) {
          if (response && response.success) {
            isPaused = true;
            pauseResumeBtn.textContent = 'Resume';
            statusText.textContent = 'Scraping paused';
          }
        }
      );
    }
  });

  // 导出数据按钮点击事件
  exportDataBtn.addEventListener('click', function () {
    chrome.runtime.sendMessage({ action: 'exportData' });
    statusText.textContent = 'Exporting data...';
  });

  // 监听抓取进度更新
  chrome.runtime.onMessage.addListener(function (message) {
    if (message.action === 'scrapeProgress') {
      // 显示当前阶段和进度
      let statusMessage = '';
      if (message.phase === 'Collecting restaurant links') {
        statusMessage = `Phase 1: ${message.phase} - ${message.current}/${message.total} pages`;
      } else if (message.phase === 'Collecting restaurant details') {
        statusMessage = `Phase 2: ${message.phase} - ${message.current}/${message.total} restaurants`;

        // 更新数据计数
        dataCount = message.current;
        dataCountText.textContent = `Collected data: ${dataCount} restaurants`;
      }

      if (isPaused) {
        statusMessage = 'PAUSED - ' + statusMessage;
      }

      statusText.textContent = statusMessage;
      const percentage = (message.current / message.total) * 100;
      progressFill.style.width = `${percentage}%`;
    } else if (message.action === 'scrapeStatusUpdate') {
      // 显示状态更新消息
      statusText.textContent = message.message;
    } else if (message.action === 'scrapeComplete') {
      statusText.textContent = `Scraping complete! Got data for ${message.count} restaurants`;
      startScrapeBtn.disabled = false;
      pauseResumeBtn.disabled = true;
      exportDataBtn.disabled = false;
      progressFill.style.width = '100%';
      isScrapingActive = false;
      isPaused = false;

      // 更新数据计数
      dataCount = message.count;
      dataCountText.textContent = `Collected data: ${dataCount} restaurants`;
    } else if (message.action === 'scrapeError') {
      statusText.textContent = `Error: ${message.error}`;
      startScrapeBtn.disabled = false;
      pauseResumeBtn.disabled = true;
      progressFill.style.width = '0%';
      isScrapingActive = false;
      isPaused = false;
    }
  });
});
